<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryFormRef" :inline="true">
      <el-form-item prop="configName" label="参数名称">
        <el-input v-model="queryForm.configName" placeholder="请输入参数名称"></el-input>
      </el-form-item>
      <el-form-item prop="configKey" label="参数键名">
        <el-input v-model="queryForm.configKey" placeholder="请输入参数键名"></el-input>
      </el-form-item>
      <el-form-item prop="configType" label="系统内置">
        <el-select v-model="queryForm.configType" placeholder="选择系统内置">
          <el-option value="Y">是</el-option>
          <el-option value="N">否</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-space>
          <el-button type="primary" @click="handleQuery()" icon="Search"> 搜索</el-button>
          <el-button @click="handleResetQuery()" icon="Refresh"> 重置</el-button>
        </el-space>
      </el-form-item>
    </el-form>

    <!-- 分割线 -->
    <el-divider />

    <div class="action">
      <el-space>
        <el-button v-has="'admin:sysConfig:add'" type="primary" @click="handleAdd" icon="Plus">新增</el-button>
        <el-button v-has="'admin:sysConfig:remove'" type="primary" status="danger" disabled icon="Delete"> 删除</el-button>
        <el-button type="primary" status="warning" disabled icon="Download"> 导出</el-button>
      </el-space>
    </div>

    <el-table :data="tableData" row-key="id" table-layout="auto">
      <el-table-column label='编码' prop='id'> </el-table-column>
      <el-table-column label='名称' prop='configName'> </el-table-column>
      <el-table-column label='键名' prop='configKey'> </el-table-column>
      <el-table-column label='内置' prop='configType'>
        <template #defalt="scope">
          <el-tag v-if="scope.row.configType === 'Y'" type="success">是</el-tag>
          <el-tag v-else-if="scope.row.configType === 'N'" type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label='备注' prop='remark' width="200"> </el-table-column>
      <el-table-column label='创建时间' prop='createdAt'>
        <template #default="scope">
          {{ parseTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label='操作' prop='action'>
        <template #default="scope">
          <el-button v-has="'admin:sysConfig:edit'" text type="primary" @click="handleUpdate(scope.row)"
            icon="Edit">修改</el-button>
          <el-button v-has="'admin:sysConfig:edit'" text type="primary"
            @click="() => { deleteVisible = true; deleteData = [scope.row.id];  }" icon="Delete"> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination :page-size="10" v-model="currentPage"  layout="prev, pager, next" :total="pager.count"
      @current-change="handlePageChange" />


    <el-dialog v-model="visible" :title="title" title-align="start" @before-ok="handleBeforeOk"
      @close="handleResetModalForm">
      <el-form :model="modalForm" :rules="rules" ref="modalFormRef">
        <el-form-item prop="configName" label="参数名称">
          <el-input v-model="modalForm.configName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item prop="configKey" label="参数键名">
          <el-input v-model="modalForm.configKey" placeholder="请输入参数键名" />
        </el-form-item>
        <el-form-item prop="configValue" label="参数键值">
          <el-input v-model="modalForm.configValue" placeholder="请输入参数键值" />
        </el-form-item>
        <el-form-item prop="configType" label="系统内置">
          <el-radio-group v-model="modalForm.configType">
            <el-radio label="Y">是</el-radio>
            <el-radio label="N">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="isFrontend" label="前台显示">
          <el-radio-group v-model="modalForm.isFrontend">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input type="textarea" v-model="modalForm.remark" placeholder="请输入备注内容"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="handleResetModalForm">取消</el-button>
          <el-button @click="handleBeforeOk" type="primary">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Akiraka 20230223 删除与批量删除 开始 -->
    <DeleteModal :data="deleteData" :visible="deleteVisible" :apiDelete="removeSysConfig"
      @deleteVisibleChange="() => deleteVisible = false" />
    <!-- Akiraka 20230223 删除与批量删除 结束 -->
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, getCurrentInstance, watch } from 'vue';
import { getSysConfig, addSysConfig, removeSysConfig, updateSysConfig } from '@/api/admin/sys-config';
import { parseTime } from '@/utils/parseTime';

const modalFormRef = ref({});
const queryFormRef = ref({});
// Akiraka 20230210 删除数据
const deleteData = ref([])
// Akiraka 20230210 删除对话框
const deleteVisible = ref(false)
// Akiraka 20230210 监听删除事件
watch(() => deleteVisible.value ,(value) => {
  if ( value == false ) {
    getSysConfigInfo(pager);
  }
})

const { proxy } = getCurrentInstance();

const currentPage = ref(1);

const pager = {
  count: 0,
  pageIndex: 1,
  pageSize: 10,
};

const { queryForm, handleQuery, handleResetQuery } = useQueryForm();
const { tableData, columns, handlePageChange, handlePageSizeChange } =
  useTableData();
const {
  rules,
  title,
  visible,
  modalForm,
  handleAdd,
  handleUpdate,
  handleBeforeOk,
} = useModal();

function useQueryForm() {
  const queryForm = reactive({});

  const handleQuery = () => {
    getSysConfigInfo(queryForm);
  };

  const handleResetQuery = () => {
    queryFormRef.value.resetFields();

    handlePageChange(1);
  };

  return {
    queryForm,
    handleQuery,
    handleResetQuery,
  };
}

function useTableData() {
  const tableData = ref([]);
  const columns = [
    { title: '编码', dataIndex: 'id', width: 70 },
    { title: '名称', dataIndex: 'configName' },
    { title: '键名', dataIndex: 'configKey' },
    {title: '内置',dataIndex: 'configType',slotName: 'configType',width: 100,},
    {title: '备注',dataIndex: 'remark',width: 350,ellipsis: true,tooltip: true,},
    { title: '创建时间', dataIndex: 'createdAt', slotName: 'createdAt' },
    { title: '操作', dataIndex: 'action', slotName: 'action' },
  ];

  // 分页改变
  const handlePageChange = (page) => {
    pager.pageIndex = page;
    getSysConfigInfo(pager);
  };

  // 每页数据量
  const handlePageSizeChange = (pageSize) => {
    pager.pageSize = pageSize;
    getSysConfigInfo(pager);
  };

  return {
    columns,
    tableData,
    handlePageChange,
    handlePageSizeChange,
  };
}

function useModal() {
  const visible = ref(false);
  const title = ref('默认标题');
  const modalForm = reactive({
    configType: 'Y',
    isFrontend: 1,
  });

  const rules = {
    configName: [{ required: true, message: '请输入参数名称' }],
    configKey: [{ required: true, message: '请输入参数键名' }],
    configValue: [{ required: true, message: '请输入参数键值' }],
  };

  const handleAdd = () => {
    visible.value = true;
    title.value = '新增参数';
  };

  const handleUpdate = async (record) => {
    visible.value = true;
    title.value = '修改参数';

    Object.assign(modalForm, record);
  };

  const handleBeforeOk = (done) => {
    modalFormRef.value.validate(async (err) => {
      if (!err) {
        try {
          const msg = await handleSubmit(modalForm);
          proxy.$message.success(msg);
          done();
          getSysConfigInfo();
        } catch (e) {
          proxy.$message.error(e);
          done(false);
        }
      } else {
        proxy.$message.error('表单校验失败');
        done(false);
      }
    });
  };

  return {
    rules,
    title,
    visible,
    modalForm,
    handleAdd,
    handleUpdate,
    handleBeforeOk,
  };
}

// 获取系统配置
const getSysConfigInfo = async (params = {}) => {
  const { data, code, msg } = await getSysConfig(params);
  if ( code == 200 ) {
    tableData.value = data.list;
    Object.assign(pager, { count: data.count, pageIndex: data.pageIndex, pageSize: data.pageSize });
  } else {
    proxy.$message.error(msg);
  }
};

// 提交
const handleSubmit = (data) => {
  return new Promise(async (resolve, reject) => {
    try {
      let res;
      if (!data.id) {
        const { code, msg } = await addSysConfig(data);
        if (code == 200 ) {
          proxy.$message.success('新增成功');
        } else {
          proxy.$message.error(msg);
        }
      } else {
        const { code, msg } = await updateSysConfig(data, data.id);
        if (code == 200 ) {
          proxy.$message.success('修改成功');
        } else {
          proxy.$message.error(msg);
        }
      }
    } catch (err) {
      reject(err);
    }
  });
};

// 重置表单
const handleResetModalForm = () => {
  modalFormRef.value.resetFields();

  modalForm.id = null;
}

onMounted(async () => {
  getSysConfigInfo();
});
</script>

<style lang="scss">
.action {
  margin-bottom: 8px;
}
</style>
